﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.IO;

namespace GeoSwarm_Editor
{
    class HardwareID
    {
        private string drive;

        public HardwareID()
        {
            drive = "C";
        }

        public HardwareID(string drive)
        {
            this.drive = drive;
        }

        public string GenerateID()
        {
            try
            {
                if (drive == string.Empty)
                {
                    //Find first drive
                    foreach (DriveInfo compDrive in DriveInfo.GetDrives())
                    {
                        if (compDrive.IsReady)
                        {
                            drive = compDrive.RootDirectory.ToString();
                            break;
                        }
                    }
                }

                if (drive.EndsWith(":\\"))
                {
                    //C:\ -> C
                    drive = drive.Substring(0, drive.Length - 2);
                }

                string cpuID = GetCpuID();
                string hdd1ID = GetHddID(drive);
                return cpuID.Substring(12) + cpuID.Substring(1, 5) + hdd1ID + cpuID.Substring(4, 4);
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        private string GetHddID(string drive)
        {
            ManagementObject dsk = new ManagementObject(@"win32_logicaldisk.deviceid=""" + drive + @":""");
            dsk.Get();
            return dsk["VolumeSerialNumber"].ToString();
        }

        private string GetCpuID()
        {
            string cpuInfo = string.Empty;
            ManagementClass mc = new ManagementClass("win32_processor");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                if (cpuInfo == "")
                {
                    //Get only the first CPU's ID
                    cpuInfo = mo.Properties["processorID"].Value.ToString();
                    break;
                }
            }
            return cpuInfo;
        }
    }
}
